<template>
  <el-container style="background: #E4E7ED;height: 100vh">
    <el-header>
      <el-page-header @back="goBack" content="创 建 群 聊" style="color: #FFFFFF">
      </el-page-header>
    </el-header>
    <el-main>
      <el-card>
        <el-form :model="groupInfo" :rules="groupInfoRule" ref="updateGroupInfoReq" label-width="100px"
          class="demo-ruleForm">
          <el-form-item label="名 称" prop="name">
            <el-input v-model="groupInfo.name"></el-input>
          </el-form-item>
          <el-form-item label="公 告" prop="text">
            <el-input v-model="groupInfo.text"></el-input>
          </el-form-item>
          <el-form-item label="图 片" prop="img_id">
            <el-select v-model="groupInfo.img_id" placeholder="请选择">
              <el-option v-for="(item, i) in imagesInfo" :key="item.info.ID" :label="i + 1" :value="i"
                style="width: 200px; height: 100px">
                <span style="width: 200px; height: 100px"><el-image style="width: 200px; height: 100px"
                    :src="item.image_http" fit="fill"></el-image></span>
                <!--                <span style="float: right; color: #8492a6; font-size: 13px">{{ item.image_http }}</span>-->
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="成员选择">
            <el-checkbox-group v-model="groupInfo.peoples_name" v-for="(item) in userInfo">
              <el-col :span="2">
                <el-checkbox-button :label="item.nick_name" @change="getChangeInfo(item.ID)"></el-checkbox-button>
              </el-col>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="updateGroup()">创 建</el-button>
            <el-button @click="resetUpdateInfo()">重 置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </el-main>
  </el-container>
</template>

<script>
export default {
  name: "groupInfo",
  data() {
    return {
      userInfo: [{
        CreatedAt: "",
        DeletedAt: "",
        ID: "",
        UpdatedAt: "",
        friends: "",
        groups: "",
        img_id: "",
        img_http: "",
        name: "",
        nick_name: "",
        password: "",
        phone: "",
        sex: "",
        text: "",
        user_id: "",
        username: "",
        login_last: "",
        status: ""
      }],
      groupInfo: {
        name: "",
        owner_id: "",
        owner_name: "",
        img_id: "",
        img_src: "",
        peoples: "",
        peoples_name: [],
        managers: "",
        msg_ids: "",
        all_msg: "",
        text: "",
      },
      groupInfoRule: {
        name: [
          { required: true, message: '⚆_⚆ 请输入名称:', trigger: 'blur' },
        ],
        img_id: [
          { required: true, message: 'ヽ(°▽°)ノ 请选择群头像:', trigger: 'blur' },
        ],
        text: [
          { required: true, message: '请输入群描述', trigger: 'blur' },
        ],
        peoples_name: [
          { required: true, message: '请选择群成员', trigger: 'change' }
        ],
      },
      imagesInfo: [{
        info: {
          CreatedAt: "",
          DeletedAt: "",
          ID: "",
          UpdateAt: "",
          author_id: "",
          format: "",
          image_id: "",
          name: "",
          size: "",
          src: "",
        },
        image_http: "",
      }],
      imgPage: {
        total: 0,
        page: 1,
        size: 10,
      },
      userList: []
    }
  },
  methods: {
    goBack() {
      this.$router.push('/index')
    },
    resetUpdateInfo() {
      this.$refs.updateGroupInfoReq.resetFields();
    },
    updateGroup() {
      let that = this;
      let token = localStorage.getItem("token")
      this.$refs.updateGroupInfoReq.validate((result) => {
        if (!result) return;
        if (that.userList.length === 0) {
          that.$message.warning("请选择好友")
          return
        }
        if (this.userList.length === 1) {
          this.groupInfo.peoples = this.userList[0] + ""
        } else {
          let str = this.userList[0] + ""
          this.userList.forEach((res, i) => {
            if (i !== 0) {
              str += "|" + res
            }
          })
          this.groupInfo.peoples = str
        }
        let index = this.groupInfo.img_id
        this.groupInfo.img_id = this.imagesInfo[index].info.ID + ""
        this.groupInfo.img_src = this.imagesInfo[index].image_http
        this.$axios({
          headers: {
            "Authorization": "Bearer " + token
          },
          method: 'post',
          url: '/group/add',
          data: JSON.stringify(that.groupInfo)
        }).then((res) => {
          let result = res.data
          if (result.code === 1005) {
            this.$message.error("群名称已存在");
            return
          }
          if (result.code === 1000) {
            this.$message({
              message: '创建成功',
              type: 'success'
            });
            that.$router.push("/index")
            return
          } else {
            this.$message.error(result.msg);
          }
        })
      });
    },
    searchAllImg() {
      let that = this
      let token = localStorage.getItem('token')
      this.$axios({
        headers: {
          "Authorization": "Bearer " + token
        },
        method: 'post',
        url: "/img/search?page=" + that.imgPage.page + "&size=" + that.imgPage.size,
      }).then((res) => {
        that.imagesInfo = res.data.data
        that.imgPage.total = res.data.count

      })
    },
    //获得当前数组中是否含有指定元素
    checkList(target) {
      let result = {}
      let show = false
      this.userList.forEach((res, i) => {
        if (res === target) {
          result.exist = true
          result.index = i
          show = true
        }
      })
      if (!show) {
        result.exist = false
        result.index = -1
      }
      return result
    },
    //删除数组中指定位置的元素
    deleteList(index) {
      let newList = []
      this.userList.forEach((res, i) => {
        if (i !== index) {
          newList.push(res)
        }
      })
      return newList
    },
    getChangeInfo(e) {
      //检查是否存在
      let result = this.checkList(e)
      console.log(result.exist)
      if (result.exist) {
        //代表本次操作时删除
        this.userList = this.deleteList(result.index)
        return
      } else {
        //代表本次操作是添加
        this.userList.push(e)
      }
    }
  },
  mounted() {
    this.userInfo = this.$route.params.data
    // console.log(this.groupInfo.peoples)
    //获得对应上传的图片
    this.searchAllImg()
  }
}
</script>

<style scoped>
.el-header {
  background-image: -webkit-linear-gradient(right, #fff1eb 0%, #ace0f9 100%);
  /*background-image: -webkit-linear-gradient(right, #a1c4fd 0%, #c2e9fb 100%);*/
}

.el-main {
  color: #333;
  text-align: center;
  /*background-image: -webkit-linear-gradient(right, #a1c4fd 0%, #c2e9fb 100%);*/
  background-image: -webkit-linear-gradient(right, #fff1eb 0%, #ace0f9 100%);
}
</style>